<template>
  <div class="menu-wrapper">
    <category-dialog ref="memberCategoryDialog" :request="'memberCategory'" @confirm="dialogConfirm" />
    <office-dialog ref="officeDialog" @confirm="officeConfirm" />
    <el-form ref="memberForm" :model="form" :rules="rules" label-width="100px">
      <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>
      <el-form-item label="客户名称" :prop="'name'" :rules="rules.name">
        <el-input v-model="form.name" placeholder="请输入客户名称" style="width: 200px" />
      </el-form-item>
      <div style="display: flex">
        <el-form-item label="注册手机" :prop="'mobile'" :rules="rules.mobile">
          <el-input v-model="form.mobile" type="Number" placeholder="请输入注册手机" style="width: 200px" />
        </el-form-item>
        <el-form-item label="会员编码" >
          <el-input v-model="form.code"  onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"  maxlength="6"  placeholder="请输入会员编码" style="width: 200px" />
        </el-form-item>
      </div>


      <div style="display: flex">
        <el-form-item label="客户等级" prop="vip">
          <el-select v-model="form.vip" style="width: 200px" placeholder="请选择类型">
            <el-option v-for="item in vips" :key="item.vip" :label="item.name" :value="item.vip" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户分类">
          <el-input v-model="form.memberCategoryName" style="width: 200px" suffix-icon="el-icon-arrow-down" @focus="dialogShow" />
        </el-form-item>
      </div>
      <el-form-item label="所在地" prop="areaId" style="width: 600px">
        <Distpicker @selected="onSelected" :province="district.province" :city="district.city"
                    :area="district.area"></Distpicker>
      </el-form-item>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="其他信息" name="otherInfo">
          <div style="display: flex">
            <el-form-item label="客户类型" prop="memberType">
              <el-select v-model="form.memberType" style="width: 200px" placeholder="请选择类型" >
                <el-option label="个人" value="0" />
                <el-option label="法人企业" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item :label="optionsType" prop="paymentPluginId">
              <el-select v-model="form.paymentPluginId" style="width: 200px" placeholder="请选择付款方式">
                <el-option
                  v-for="item in optionsForm"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="备用电话" prop="phone">
              <el-input v-model="form.phone" style="width: 500px" />
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="所属企业">
              <el-select v-model="form.companyId" style="width: 200px" filterable :filter-method="productMethod" placeholder="请选择企业">
                <el-option
                  v-for="item in companyList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="电子邮箱">
              <el-input v-model="form.email" style="width: 200px" />
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="所属部门" prop="officeName">
              <el-input v-model="officeName" style="width: 200px" suffix-icon="el-icon-arrow-down" @focus="officeShow" />
            </el-form-item>
            <el-form-item label="推荐人名" prop="officeName">
              <el-select
                v-model="promoterName"
                style="width: 200px"
                :filter-method="remoteMethod"
                value-key="id"
                filterable
                placeholder="请选择"
                @change="changMember"
              >
                <el-option
                  v-for="item in memberList"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </div>

<!--          <el-form-item label="详细地址" prop="address" style="width: 550px">-->
<!--              <el-input v-model="form.address"/>-->
<!--          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" :loading="clicked" @click="updateMember('memberForm')">
              完 成
            </el-button>
          </el-form-item>
        </el-tab-pane>
        <!--        <el-tab-pane label="收货地址" name="address">-->
        <!--          <div style="display: flex; justify-content: flex-end; margin-bottom: 10px; width: 100%;">-->
        <!--            <el-button type="primary"-->
        <!--                       @click="goReceiver">新增/修改-->
        <!--            </el-button>-->
        <!--          </div>-->
        <!--          <el-table-->
        <!--            :data="receiverList"-->
        <!--            border-->
        <!--            stripe-->
        <!--            v-loadMore="[payLoads,'receiver-list']"-->
        <!--            style="width: 100%">-->
        <!--            <el-table-column-->
        <!--              label="收货人"-->
        <!--              align="left"-->
        <!--              prop="consignee"-->
        <!--              width="100"-->
        <!--            >-->
        <!--            </el-table-column>-->
        <!--            <el-table-column-->
        <!--              label="联系电话"-->
        <!--              align="left"-->
        <!--              prop="phone"-->
        <!--              width="110"-->
        <!--            >-->
        <!--            </el-table-column>-->
        <!--            <el-table-column-->
        <!--              label="收货地址"-->
        <!--              align="left"-->
        <!--              prop="areaName"-->
        <!--            >-->
        <!--            </el-table-column>-->
        <!--            <el-table-column-->
        <!--              label="详细地址"-->
        <!--              align="left"-->
        <!--              prop="address"-->
        <!--            >-->
        <!--            </el-table-column>-->
        <!--            <el-table-column-->
        <!--              label="小区/大楼"-->
        <!--              align="left"-->
        <!--              prop="building"-->
        <!--              width="100"-->
        <!--            >-->
        <!--            </el-table-column>-->
        <!--            <el-table-column-->
        <!--              label="门牌号码"-->
        <!--              align="left"-->
        <!--              prop="roomNumber"-->
        <!--              width="80"-->
        <!--            >-->
        <!--            </el-table-column>-->
        <!--          </el-table>-->
        <!--        </el-tab-pane>-->
        <!-- <el-tab-pane label="钱包账单" name="deposit">
          <div v-for="item in depositList">
            <div class="deleted_OrderHeader">
              <el-row :gutter="24">
                <el-col :span="1">
                  <span style="padding-left: 20px;">├</span>
                </el-col>
                <el-col :span="4">
                  <span>{{item.createDate | datetimeFormatter}}</span>
                </el-col>
                <el-col :span="13">
                  <span>{{item.memo}}</span>
                </el-col>
                <el-col :span="3" v-if="item.credit">
                  <span>收入 : {{item.credit}}</span>
                </el-col>
                <el-col :span="3" v-else>
                  <span style="color: red;">支出 : {{item.debit}}</span>
                </el-col>
                <el-col :span="3">
                  <span>余额 : {{item.balance}}</span>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="积分账单" name="point">
          <div v-for="item in pointList">
            <div class="deleted_OrderHeader">
              <el-row :gutter="24">
                <el-col :span="1">
                  <span style="padding-left: 20px;">├</span>
                </el-col>
                <el-col :span="4">
                  <span>{{item.createDate | datetimeFormatter}}</span>
                </el-col>
                <el-col :span="13">
                  <span>{{item.memo}}</span>
                </el-col>
                <el-col :span="3" v-if="item.credit">
                  <span>收入 : {{item.credit}}</span>
                </el-col>
                <el-col :span="3" v-else>
                  <span style="color: red;">支出 : {{item.debit}}</span>
                </el-col>
                <el-col :span="3">
                  <span>余额 : {{item.balance}}</span>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane> -->
      </el-tabs>
    </el-form>
  </div>
</template>
<style scoped lang="scss">
  .menu-wrapper {
    margin: 15px;
  }
  .deleted_OrderHeader {
    padding-top: 5px;
    padding-bottom: 10px;
    margin: 10px 0;
    border-left: 1px solid #f2f2f2;
    border-bottom: 1px solid #f2f2f2;
  }
</style>
<script>

import { list as memberList } from '@/api/member'
import OfficeDialog from '@/components/OfficeDialog'
import loadMore from '@/utils/loadMore.js'
import permission from '@/directive/permission/index.js' // 权限判断指令
import { list } from '../../api/vip'
import { EventBus } from '@/api/eventBus'
import utils from '../../utils/utils.js'
import Distpicker from '@/components/Distpicker/Distpicker'
import { update, find, deposit, point, receiver } from '@/api/member'
import { checkUserExists } from '@/api/sysUser'
import md5 from 'js-md5'
import CategoryDialog from '@/components/CategoryDialog'
import { list as companys } from '../../api/company'

export default {
  name: 'MemberEdit',
  filters: {},
  directives: { permission, loadMore },
  components: {
    Distpicker, CategoryDialog, OfficeDialog
  },
  data() {
    return {
      promoterName: '',
      officeName: '',
      memberList: [],
      id: '',
      activeName: 'otherInfo',
      payLoads: '',
      vips: [],
      companyList: [],
      clicked: false, // 按钮防双击
      district: {},
      receiverList: [],
      depositList: [],
      pointList: [],
      form: {
        officeId: '',
        companyId: '',
        balance: 0,
        paymentPluginId:'',
        point: 0,
        code:'',
        name: '',
        birth: '',
        mobile: '',
        phone: '',
        email: '',
        gender: '0',
        areaId: 440000,
        areaName: '广东省广州市海珠区',
        address: '',
        vip: '',
        memberCategoryId: '',
        memberType: '0'
      },
      vipName: '',
      memberCategoryName: '',
      dateName: '出生日期',
      optionsType: '付款方式',
      optionsForm: [
        { name: '现金客户', value: 'cashPayPlugin' },
        { name: '月结客户', value: 'debtPayPlugin'},
      ],
      rules: {
        name: [
          { required: true, message: '请输入商户名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        vip: [
          { required: true, message: '请选择客户等级', trigger: 'blur' }
        ]
      },
      flowing: []
    }
  },
  watch: { // 路由地址不变的情况下,如果id变化则重新获取数据
    $route(newVal, oldVal) {
      console.log(newVal)
      if (newVal.name == 'member-edit' && newVal.query.id != this.id) {
        this.getData()
      }
    }
  },
  activated() {
    this.payLoads = new Date().getTime()
  },
  created() {
    this.loadCompany('')
    this.loadMember('')
    this.getData()
  },
  methods: {
    changMember(data) {
      this.form.promoterId = data.id
      this.promoterName = data.name
    },
    // 会员选择
    loadMember(query) {
      var _this = this
      const params = new URLSearchParams()
      params.append('name', query)
      memberList(params).then(response => {
        console.log(response)
        _this.memberList = response.data.data
      }).catch(error => {
        console.log('error!!')
      })
    },
    officeConfirm(val) {
      this.form.officeId = val.id
      this.officeName = val.name
    },
    remoteMethod(query) {
      this.loadMember(query)
    },
    productMethod(query) {
      this.loadCompany(query)
    },
    officeShow() {
      console.log('点击了')
      this.$refs.officeDialog.show()
    },
    loadCompany(query) {
      companys({ name: query }).then(res => {
        this.companyList = res.data.data
      })
    },
    getData() {
      this.activeName = 'otherInfo'
      this.id = this.$route.query.id
      this.loadVip()
      var _this = this
      find(_this.id).then(response => {
        console.log(response)
        if (response.type == 'success') {
          _this.form.id = _this.$route.query.id
          _this.officeName = response.data.officeName
          _this.promoterName = response.data.promoterName
          _this.form.promoterId = response.data.member.promoterId
          _this.form.paymentPluginId=response.data.member.paymentPluginId
          _this.form.officeId = response.data.member.officeId
          _this.form.point = response.data.point
          _this.form.code=response.data.member.code
          _this.form.companyId = response.data.member.companyId
          _this.form.balance = response.data.balance
          _this.form.name = response.data.member.name
          _this.form.birth = response.data.member.birth
          _this.form.mobile = response.data.member.mobile
          _this.form.phone = response.data.member.phone
          _this.form.email = response.data.member.email
          _this.form.gender = JSON.stringify(response.data.member.gender)
          _this.form.areaName = response.data.member.areaName
          _this.form.areaId = response.data.member.areaId
          _this.form.address = response.data.member.address
          _this.form.vip = response.data.member.vip
          _this.district = {}
          const reg = /.+?(省|市|自治区|自治州|县|区)/g
          _this.district.province = _this.form.areaName.match(reg)[0]
          _this.district.city = _this.form.areaName.match(reg)[1]
            _this.district.area = _this.form.areaName.match(reg)[2]
          console.log(_this.form.areaName.match(reg))
          // _this.vipName = 'vip'+JSON.stringify(response.data.vip);
          _this.vipName = response.data.member.vip
          // _this.memberCategoryName = response.data.memberCategoryName;
          _this.form.memberCategoryName = response.data.member.memberCategoryName
          _this.form.memberCategoryId = response.data.member.memberCategoryId
          // _this.district = utils.decodeArea(response.data.areaId);


        } else {
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          })
        }
      }).catch(error => {
      })
    },
    handleClick(tab, event) {
      console.log(tab, event)
      if (tab.index == 1) {
        console.log('地址')
        receiver({ memberId: this.id }).then(res => {
          console.log(res)
          this.receiverList = res.data.data
        }).catch(err => {
          console.log(err)
        })
      } else if (tab.index == 2) {
        deposit({ memberId: this.id }).then(res => {
          console.log(res)
          this.depositList = res.data.data
        })
      } else if (tab.index == 3) {
        point({ memberId: this.id }).then(res => {
          console.log(res)
          this.pointList = res.data.data
        }).catch(err => {
          console.log(err)
        })
      }
    },
    loadVip() {
      list().then(res => {
        this.vips = res.data.data
      })
    },
    onSelected(val) {

      if (!utils.isNull(val.area) && !utils.isNull(val.area.code)) {
        this.form.areaId = val.area.code
        this.form.areaName = val.province.value+val.city.value+val.area.value
      }else if (!utils.isNull(val.city) && !utils.isNull(val.city.code)){
        this.form.areaId = val.city.code
        this.form.areaName = val.province.value+val.city.value

      }else if (!utils.isNull(val.province) && !utils.isNull(val.province.code)){
        this.form.areaId = val.province.code
        this.form.areaName = val.province.value
      }


    },
    dialogShow() {
      console.log('点击了')
      this.$refs.memberCategoryDialog.show()
    },
    dialogConfirm(val) {
      console.log(val)
      this.memberCategoryName = val.name
      this.form.memberCategoryId = val.id
    },
    updateMember(form) {
      const _this = this
      this.$refs[form].validate((valid) => {
        if (valid) { // 校验表单
          _this.clicked = true
          _this.form.birth = ''
          update(_this.form).then(response => {
            console.log(response)
            _this.clicked = false
            if (response.type == 'success') {
              EventBus.$emit('member-edit', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({ visitedViews }) => {
                _this.$router.push({
                  path: '/member/list'
                })
              })// 关闭当前tab回到列表
            } else {
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              })
            }
          }).catch(error => {
            _this.clicked = false
          })
        } else {
          return false
        }
      })
    },
    memberTypeClick(val) {
      console.log(val)
      var _this = this
      if (val == 0) {
        _this.dateName = '出生日期'
        _this.optionsType = '性别'
        _this.optionsForm = [
          { name: '男', value: 0 },
          { name: '女', value: 1 },
          { name: '隐藏', value: 2 }
        ]
      } else {
        _this.dateName = '创建日期'
        _this.optionsType = '企业类型'
        _this.optionsForm = [
          { name: '企业', value: 1 },
          { name: '事业单位', value: 2 }
        ]
      }
    },
    goReceiver() {
      this.$router.push({
        path: '/receiver/list', query: { memberId: this.$route.query.id }
      })
    }
  }
}
</script>
